package com.force.abril.api.maintanence.client;

import javax.annotation.PostConstruct;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import br.com.abril.sforce.ProxyChanged;
import br.com.abril.sforce.ProxyEntry;

import com.force.provider.SalesForceConnectionProvider;

@Component
public class HttpClientProxyConfiguration implements
		ApplicationListener<ProxyChanged> {

	@Autowired
	@Qualifier("bookingMaintenanceHttpClient")
	private HttpClient httpClient;

	@Autowired
	private SalesForceConnectionProvider connectionProvider;

	public HttpClientProxyConfiguration() {

	}

	@PostConstruct
	public void setUpHttpClient() {
		httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());
		setHttpClientProxy();
	}

	public void setHttpClientProxy() {

		ProxyEntry proxyTemplate = getProxyEntry();
		if (proxyTemplate == null || !proxyTemplate.getEnabled())
			return;

		HostConfiguration confg = httpClient.getHostConfiguration();
		confg.setProxy(proxyTemplate.getHost(), proxyTemplate.getIntPort());

		Credentials credentials = new UsernamePasswordCredentials(
				proxyTemplate.getUser(), proxyTemplate.getPassword());

		httpClient.getState().setProxyCredentials(AuthScope.ANY, credentials);
	}

	public ProxyEntry getProxyEntry() {
		return connectionProvider.getProxyProvider().getProxyEntry();
	}

	@Override
	public void onApplicationEvent(ProxyChanged event) {
		setHttpClientProxy();
	}

}
